import { reactive, onMounted } from 'vue';
import { notification } from 'ant-design-vue';
export const defaultContext = {
  loading: false,
  page: 1,
  limit: 20,
  total: 0,
  dataSource: [],
}; // 如果请求数据中，没有分页，仅单列表数据，可以使用该方法进行包装，免去重复写请求方法

export const handlerData = req => {
  const state = reactive({
    loading: false,
  });

  return (options = {}, message) => {
    if (state.loading) {
      return;
    }
    state.loading = true;
    return req(options)
      .then(res => {
        state.response = res;
        state.loading = false;
        message && notification.success(message);
        return {
          state,
          success: state !== null && state !== undefined,
        };
      })
      .catch(() => {
        state.loading = false;
      });
  };
};

export const useGetList = (apiGetData, context, options) => {
  const state = reactive({ ...defaultContext, ...context });

  const getList = async () => {
    // 请求中禁止重复请求
    if (state.loading) return;

    state.loading = true;
    const { limit = 20, page = 1 } = state;

    try {
      const params =
        options?.pagination !== false
          ? {
              page,
              limit,
              ...state.requestParams,
            }
          : undefined;
      //   const { data, success, total: dataTotal = 0 } = await apiGetData(params);
      const {
        code,
        page: { list, totalCount },
      } = await apiGetData(params);

      const listMap = list.map(item => {
        const { filters } = options;
        if (filters) {
          const keys = Object.keys(filters);
          keys.forEach(key => {
            item[key] = filters[key](item[key]);
          });
        }
        return item;
      });

      if (code === 0) {
        state.dataSource = listMap;
        state.total = totalCount;
      }
    } catch (e) {
      if (options?.onRequestError === undefined) {
        throw new Error(e);
      } else {
        options.onRequestError(e);
      }
    } finally {
      state.loading = false; // 如果没有传递这个方法的话，需要把错误抛出去，以免吞掉错误
    }
  };

  const reload = () => {
    return new Promise(resolve => {
      resolve(getList());
    });
  };

  const resetParams = pageInfo => {
    pageInfo.page && (state.page = pageInfo.page);
    pageInfo.limit && (state.limit = pageInfo.limit);
    state.requestParams = pageInfo;
    reload();
  };

  const resetPageIndex = () => {
    state.page = 1;
  };

  onMounted(() => {
    getList().catch(e => {
      console.dir(e);
      throw new Error(e);
    });
  });
  return {
    reload,
    resetPageIndex,
    resetParams: info => {
      resetParams({
        page: state.page,
        limit: state.limit,
        ...info,
      });
    },
    context: state,
  };
};
